/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: javaseapp - Ex3
 * <p>Powered by webrx On 2021-08-25 08:59:35
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class Ex3 {
    static List<String> list = new ArrayList<String>();
    static CountDownLatch latch = new CountDownLatch(1);

    public static void work() {
        String tn = Thread.currentThread().getName();
        System.out.println(tn + ":线程启动");
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            list.add("item" + (list.size() + 1));
            System.out.println(String.format("%s:%d = %s", tn, list.size(), list.get(list.size() - 1)));
            if (list.size() == 5) {
                latch.countDown();//开启门栓，此时会提醒线程二向下执行。
            }
        }
    }

    public static void check() {
        String tn = Thread.currentThread().getName();
        System.out.println(tn + ":线程启动");
        try {
            latch.await();//此线程中断在此处，等待
            System.out.println(tn + ":容器中已经有五个元素了,线程结束 。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //CountDownLatch
        //T1 任务向容器中添加元素，到5个元素时，打开门栓通知线程T2
        new Thread(Ex3::work, "T1").start();
        //T2 启动就进入就绪等待，接到通知就开始向下执行。
        new Thread(Ex3::check, "T2").start();
    }
}
